package com.heaven.service.impl;

import cn.dev33.satoken.session.SaSession;
import cn.dev33.satoken.stp.StpUtil;
import com.heaven.constant.SaTokenConstants;
import com.heaven.core.entity.UserEntity;
import com.heaven.customerServer.customerController.vo.login.LoginRes;
import com.heaven.service.LoginService;
import com.heaven.service.UserService;
import com.heaven.service.minio.MinIoService;
import com.heaven.utils.BeanUtils;
import com.heaven.utils.RedisUtils;
import com.heaven.utils.StringUtils;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

@Service("loginService")
@Slf4j
public class LoginServiceImpl implements LoginService {
    @Resource
    private UserService userService;
    @Resource
    private RedisUtils redisUtils;
    @Resource
    private MinIoService minIoService;

    @Override
    public LoginRes loginWithPwd(String username, String password) {
        Query query = new Query();
        query.addCriteria(new Criteria().orOperator(
                Criteria.where("phone").is(username),
                Criteria.where("email").is(username)));
        UserEntity userEntity = userService.selectOne(query);
        if (userEntity == null) {
            return new LoginRes(false);
        }
        BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        if (passwordEncoder.matches(password, userEntity.getPassword())) {
            StpUtil.login(username);
            // 密码正确
            LoginRes.UserSession userSession = new LoginRes.UserSession();
            BeanUtils.copyProperties(userEntity, userSession);

            // 创建userSession, 存放用户的基本信息
            StpUtil.getSession().set(SaTokenConstants.USER_SESSION_KEY, userSession);
            String token = StpUtil.getTokenValue();

            userEntity = userService.initUser(userEntity);
            BeanUtils.copyProperties(userEntity, userSession);

            return new LoginRes(true, token, userSession);
        } else {
            return new LoginRes(false);
        }
    }

    @Override
    public LoginRes.UserSession getUserSessionByTokenWithRedis(String token) {
        Object loginId = StpUtil.getLoginIdByToken(token);
        if (loginId == null) {
            return null;
        }
        SaSession saSession = StpUtil.getSessionByLoginId(loginId, false);

        LoginRes.UserSession userSession = saSession.getModel(SaTokenConstants.USER_SESSION_KEY, LoginRes.UserSession.class);
        // 转化为将minio的外部访问格式
        String headerUrl = minIoService.getLink(userSession.getHeader());
        userSession.setHeader(headerUrl);
        return userSession;

    }
}
